package com.darren.euc.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSON;
import com.darren.euc.entity.Member;
import com.darren.euc.entity.MemberMould;
import com.darren.euc.entity.PageBean;
import com.darren.euc.entity.ResponseJSON;
import com.darren.euc.entity.Room;
import com.darren.euc.entity.User;
import com.darren.euc.service.HanWangDoorService;
import com.darren.euc.service.MemberService;
import com.darren.euc.service.RoomService;
import com.darren.euc.util.Constant;
import com.darren.euc.util.EncryptAESUtil;
import com.darren.euc.util.ExcelToJson;
import com.darren.euc.util.FileUploadUtils;
import com.darren.euc.util.PropertyConfigurer;
import com.darren.euc.util.PropertyHelper;
import com.darren.euc.util.StringUtil;
import com.google.common.collect.Lists;

import net.sf.json.JSONObject;


/**
 * Created by yanglas on 2018/3/11.
 */
@Controller
@RequestMapping("/member")
public class MemberAction {
    private static final Logger log = Logger.getLogger(MemberAction.class);
//
//    @Value("#{properties.haqi.url}")
//    private String HAQI_URL;

    @Autowired
    private MemberService memberService;
    
    @Autowired
    private HanWangDoorService hanWangDoorService;

    @Autowired
    private RoomService roomService;
    
    /**
     * 保存会员
     * @param member
     * @param response
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value= "/add",method = RequestMethod.POST)
    public ResponseJSON saveMember(@RequestBody Member member, HttpServletResponse response, HttpServletRequest request){
        //表单提交
        User user = (User) request.getAttribute("user");
        if(user != null){
            member.setCreatedBy(user.getUserName());
            member.setLastModifyBy(user.getUserName());
        }
        Member persistent = null;
        try {
            persistent = memberService.saveMember(member);
            if(persistent != null){
                return  ResponseJSON.defaultSuccessResponse();
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new ResponseJSON().set(-1,e.getMessage(),null);
        }

        return ResponseJSON.defaultFailedResponse();
    }

    /**
     * 查询
     * @param requestJson
     * @param request
     * @param response
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/query",method = RequestMethod.POST)
    public ResponseJSON queryMember(@RequestBody JSONObject requestJson, HttpServletRequest request, HttpServletResponse response) {
        ResponseJSON responseJson = new ResponseJSON();
        PageBean pageBean = memberService.queryForPageUseHQL(requestJson.getJSONObject("data"), PropertyHelper.getPageSize(), requestJson.getInt("currentPage"));
        responseJson.setData(pageBean);
        return responseJson;
    }

    /**
     * 删除与离场
     * @param requestJson
     * @param request
     * @param response
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/deleteOrBroken",method = RequestMethod.POST)
    public ResponseJSON deleteOrBroken(@RequestBody JSONObject requestJson,
                                       HttpServletRequest request,
                                       HttpServletResponse response) {
        ResponseJSON responseJson = new ResponseJSON();
        String result = hanWangDoorService.unbindingCard(requestJson.getInt("memberId"));
        if(!"".equals(result)){
    		//return new ResponseJSON(Constant.STATUS_FAIL,result,null);
    	} 
        Member member = memberService.updateStatus(requestJson.getInt("memberId"),requestJson.getInt("status"));       
        responseJson.setData(member);
        return responseJson;
    }

    /**
     * 绑定手环
      * @return
     */
    @ResponseBody
    @RequestMapping(value = "/bindWristBand")//,method = RequestMethod.POST)
    public ResponseJSON bindWristBands(@RequestParam(name = "wristBandsNumber",required = true) String wristBandsNumber,@RequestParam(name = "memberId",required = true) Integer memberId){
        //wristBandsNumber，和对应的memberId
        try{
        	List<Room> rooms = roomService.findRooByMemberIdWithoutTimeLimit(memberId);
        	if(rooms != null && rooms.size() > 0){
        		memberService.bindWristBrindsNumber(wristBandsNumber,memberId);
                String result = hanWangDoorService.bindingCard(memberId);
                if(!"".equals(result)){
                	if(result.startsWith("会员") 
                			|| result.startsWith("连接主设备【") 
                			||  result.startsWith("主设备【") 
                			|| result.startsWith("向主设备【") 
                			|| "未找到主设备!".equals(result)){
                		memberService.cancelBind(memberId);
                		return new ResponseJSON(Constant.STATUS_FAIL,"绑卡失败\r\n"+result,null);
                	}else{
                		return new ResponseJSON(Constant.STATUS_SUCCESS,"绑卡完成\r\n"+result,null);
                	}
            	} 
                return new ResponseJSON(Constant.STATUS_SUCCESS,"绑定成功",null); 
        	}else{
        		return new ResponseJSON(Constant.STATUS_FAIL,"绑定失败，该会员没有绑定工位。",null); 
        	}                       
        }catch (Exception e){
            return new ResponseJSON(-1,e.getMessage(),null);
        }
    }
    /**
     * 解绑手环
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/cancelBind")//,method = RequestMethod.POST)
    public ResponseJSON cancelBind(@RequestParam(name = "memberId",required = true) Integer memberId){
        try{            
            String result = hanWangDoorService.unbindingCard(memberId);
            if(!"".equals(StringUtil.convertNullToEmptyString(result))){
            	if(result.startsWith("会员") || "未找到主设备!".equals(result)){
            		return new ResponseJSON(Constant.STATUS_FAIL,"解绑失败\r\n"+result,null);
            	}else{
            		memberService.cancelBind(memberId);
            		return new ResponseJSON(Constant.STATUS_SUCCESS,"解绑完成\r\n"+result,null);
            	}        		
        	} 
            memberService.cancelBind(memberId);
            return new ResponseJSON(Constant.STATUS_SUCCESS,"解绑成功",null);
        }catch (Exception e){
            return new ResponseJSON(-1,e.getMessage(),null);
        }

    }


    /**
     * 查看详情
     * @param member
     * @return
     */
    @ResponseBody
    @RequestMapping(value= "/detail",method = RequestMethod.POST)
    public ResponseJSON queryDetail(@RequestBody Member member){
        ResponseJSON responseJson = ResponseJSON.defaultSuccessResponse();
        Member detail = memberService.findByMemberId(member.getId());
        if(detail != null){
            responseJson.setData(detail);
        }else{
            return ResponseJSON.defaultFailedResponse();
        }
        return responseJson;
    }

    /**
     * 上传头像，返回头像地址
     * @param file
     * @param request
     * @return
     * @throws IOException
     */
    @ResponseBody
    @RequestMapping(value = "/upload",method = RequestMethod.POST)
    public ResponseJSON uploadPhoto(MultipartFile file,HttpServletRequest request) throws IOException {
       // String path = request.getScheme()+"://"+request.getRemoteHost()+":"+request.getServerPort();
        String path = PropertyConfigurer.getPropertiesStr("server.ip")+":"+request.getServerPort();
        String headUrl = request.getSession().getServletContext().getContextPath()+"/"+FileUploadUtils.uploadFile(file, request,"images");
        return ResponseJSON.defaultSuccessResponse(path + headUrl);
    }

    /**
     * 上传xls文件
     * @param file
     * @param request
     * @return
     * @throws IOException
     */
    @ResponseBody
    @RequestMapping(value = "/uploadXls",method = RequestMethod.POST)
    public ResponseJSON batchImport(@RequestParam("file") MultipartFile file, HttpServletRequest request) throws IOException {
        String filepath =  FileUploadUtils.uploadFile(file,request);
        return ResponseJSON.defaultSuccessResponse(filepath);
    }

    /**
     * 导出模板
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("/exportExcel")
    public void exportExcel(HttpServletRequest request, HttpServletResponse response) {
        File file;
        FileInputStream inputStream = null;
        try {
            String fileName = "模板文档_第一行不能变.xls";
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
            OutputStream outputStream = response.getOutputStream();
            file = ResourceUtils.getFile("classpath:mould.xls");
            inputStream = new FileInputStream(file);
            byte[] buff = new byte[1024];
            int index = 0;
            while ((index = inputStream.read(buff, 0, 1024)) > 0) {
                outputStream.write(buff, 0, index);
            }
            outputStream.flush();
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            IOUtils.closeQuietly(inputStream);
        }
    }


    /**
     * 批量导入
     * @param request
     * @return
     * @throws IOException
     */
    @ResponseBody
    @RequestMapping(value = "/batchImport",method = RequestMethod.GET)
    public ResponseJSON batchImport(@RequestParam("file_path") String file_path,
                                    @RequestParam("client_id") Integer clientId,
                                    @RequestParam("space_id") Integer spaceId,
                                    HttpServletRequest request) throws IOException {
        User user = (User) request.getAttribute("user");
        ExcelToJson excelToJson = new ExcelToJson();
        String jsonResult = null;
        try {
            jsonResult = excelToJson.doExcelToJson(file_path, 0, 0);
        }catch (Exception e){
            e.printStackTrace();
            return new ResponseJSON(-1,"导入失败",null);
        }
        List<MemberMould> memberMoulds = JSON.parseArray(jsonResult, MemberMould.class);
        List<Member> members = Lists.newArrayList();
        memberMoulds.forEach(memberMould -> members.add(memberMould2Member(memberMould,clientId,spaceId,user)));
        try{
            memberService.saveMembers(members);
        }catch (Exception e){
            return new ResponseJSON().set(-1,e.getMessage());
        }
        return ResponseJSON.defaultSuccessResponse();
    }

    public static Member memberMould2Member(MemberMould memberMould,Integer clientId, Integer spaceId,User user) {
        if (memberMould == null) {
            return null;
        }
        Member member = new Member();
        member.setMobile(memberMould.getMobile());
        member.setIdCard(memberMould.getIdCard());
        member.setEmail(memberMould.getEmail());
        member.setName(memberMould.getName());
        member.setNickName(memberMould.getNickName());
        member.setFaceUrl(memberMould.getFaceUrl());
        member.setEmployStatus(memberMould.getEmployStatus());
        member.setIsAdmin(memberMould.getIsAdmin());
        member.setClientId(clientId);
        member.setSpaceId(spaceId);
        member.setCreatedBy(user.getName());
        String _password = EncryptAESUtil.getEncryption(memberMould.getPassword(), PropertyHelper.getEncryptKey());
        member.setPassword(_password);
        member.setDeptId(memberMould.getDeptId());
        member.setCreateTime(new Date());
        return member;
    }


}
